<?php
declare (strict_types=1);

namespace app\controller;

use app\helpers\MyCodeService;
use app\model\User;
use app\traits\JsonResponse;
use think\exception\ValidateException;
use think\Request;
use think\facade\Request as RequestFacade;

class Auth {
    use JsonResponse;
    public function register(Request $request,User $user) {
        try {
            validate([
                'name|用户名称'  => 'require|max:255',
                'phone|手机号'   => 'require|regex:/^1[3589]\d{9}$/|unique:user',
                'email|邮箱'     => 'require|email|unique:user',
                'password|密码'  => 'require|min:6|confirm',
                'code|验证码'    => 'require|integer'

            ])->batch()->check($request->post());
            $phone = $request->post('phone');
            if(!app(MyCodeService::class)->checkCode($phone,$request->post('code'))){
                return $this->jsonFail(message:'手机验证码输入错误');
            }
            $user->name = $request->post('name');
            $user->phone = $phone;
            $user->email = $request->post('email');
            $user->avatar = RequestFacade::domain().'/fakes/avatars/avatar'.mt_rand(1,7).'.png';
            $user->password = getSha1Password($request->post('password'));
            $user->save();
            return $this->jsonSuccess($user,'注册成功',201);
        } catch (ValidateException $e) {
            return $this->jsonFail($e->getError(),'输入信息不合法',422);
        }
    }

    public function login(Request $request) {
            $phone = $request->post('phone');
            if(!userExist($phone)){
                return $this->jsonFail(message:'用户手机不存在');
            }
        try {
            validate([
                'phone|手机号'   => 'require|regex:/^1[3589]\d{9}$/',
                'password'      => 'require|min:6',
            ])->batch()->check($request->post());
            $user = User::where('phone',$phone)->findOrEmpty();
            if(!$user->isEmpty() && $user->password == getSha1Password($request->post('password'))){
                return $this->jsonSuccess(['token'=>$user->makeToken()]);
            }
            return $this->jsonFail(message:'手机号或密码错误');
        } catch (ValidateException $e) {
            return $this->jsonFail($e->getError(),'输入信息不合法',422);
        }
    }
}
